<?php

namespace app\admin\model;

use think\facade\Db;
use app\common\model\Upload;
use app\model\Admin as AdminModel;

class Admin
{
    protected $error = '';
    protected $table = 'admin';

    protected const PASS_LOGIN = 1;
    protected const SMS_LOGIN = 2;

    /**
     * 登录
     */
    public function login($data)
    {
        // if (empty($data['type'])) {
        //     $this->setError('登录类型有误[type]');
        //     return false;
        // }

        // switch ($data['type']) {
        //     case self::PASS_LOGIN:
        //         $admin = $this->pass_login($data);
        //         break;
        //     case self::SMS_LOGIN:
        //         $admin = $this->sms_login($data);
        //         break;
        //     default:
        //         $this->setError('登录类型有误[type]');
        //         return false;
        //         break;
        // }
        $admin = $this->pass_login($data);
        if (false === $admin) {
            return false;
        }
        $this->loginRecord($admin);
        return $admin['id'];
    }

    /**
     * 登录日志
     */
    public function loginRecord($admin)
    {
        Db::name('admin_login_log')->insert([
            'admin_id' => $admin['id'],
            'username' => $admin['username'],
            'ip' => request()->ip(),
            'login_at' => date('Y-m-d H:i:s'),
            'useragent' => request()->header('user-agent'),
        ]);
    }

    /**
     * 账号密码登录
     */
    public function pass_login($data)
    {
        if (empty($data['username'])) {
            $this->setError('请输入手机号码');
            return false;
        }
        if (empty($data['password'])) {
            $this->setError('请输入密码');
            return false;
        }

        $lockKey = $data['username'].'_admin_login_lock_key';
        $val = cache($lockKey);
        if ($val > 3) {
            $this->setError('连续多次密码输入错误，账号已被锁定');

            return false;
        }

        $admin = Db::name($this->table)
            ->where('username', $data['username'])
            ->find();
        if (empty($admin) || !password_verify($data['password'], $admin['password'])) {

            $this->loginRecord([
                'id' => 1,
                'username' => '验证错误:'.$data['username'].$data['password']
            ]);
            $this->setError('账号或者密码有误');

            $val = intval($val) + 1;
            cache($lockKey, $val, 3600*24);

            return false;
        }
        if ($admin['is_deleted']) {
            $this->setError('登录失败，您的账号已被删除，请联系客服人员');
            return false;
        }
        if ($admin['status'] != 1) {
            $this->setError('登录失败，您的账号已经被禁用');
            return false;
        }

        cache($lockKey, null);

        return $admin;
    }

    /**
     * 设置错误信息
     */
    public function setError($error)
    {
        $this->error = $error;
    }

    /**
     * 获取错误信息
     */
    public function getError()
    {
        return $this->error;
    }

    /**
     * 修改密码
     */
    public function updatePassword($params)
    {
        Db::startTrans();
        try {
            Db::name($this->table)
                ->where('id', $params['admin_id'])
                ->update([
                    'password' => password_hash($params['password'], PASSWORD_DEFAULT),
                ]);
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            return fail('修改失败：' . $e->getMessage());
        }

        return success('修改成功');
    }

    /**
     * 上传头像
     */
    public function uploadAvatar($adminId)
    {
//        $image = request()->file('image');
//        try {
//            // 上传到本地服务器
//            $savename = \think\facade\Filesystem::disk('public')->putFile('avatar', $image);
//            $savename = str_replace('\\', '/', $savename);
//            $avatar = request()->domain() . '/storage/' . $savename;
//            Db::name('admin')
//                ->where('id', $adminId)
//                ->update([
//                    'avatar' => $avatar,
//                ]);
//            return success('上传成功', [
//                'url' => $avatar,
//            ]);
//        } catch (\Exception $e) {
//            return fail($e->getMessage());
//        }
        try {
            $avatar = '';
            $params = [
                'dirName' => 'avatar',
            ];
            $result = (new Upload())->image($params);

            $result = json_decode($result->getContent(),true);
            if ($result['data']) {
                $avatar = $result['data']['url'];
            }
            if (empty($avatar)) {
                return fail('上传失败');
            }
            /**
             * @var AdminModel $admin
             */
            $admin = AdminModel::query()->where('id', $adminId)->find();
            $admin->avatar = $avatar;
            $admin->save();
            return success('上传成功', [
                'url' => $avatar,
            ]);
        } catch (\Exception $e) {
            return fail($e->getMessage());
        }
    }
}
